<template>
  <div>
    <h1>智能问题</h1>
    <div>
      <el-input
        v-model="chatMessage"
        type="textarea"
        :rows="10"
        placeholder="聊天内容"
      ></el-input>
    </div>
    <div>
      <el-input
        v-model="sendMessage"
        type="textarea"
        :rows="2"
        placeholder="消息发送"
      ></el-input>
    </div>
    <div>
      <el-row>
        <el-button type="info" round @click="handleConnect">连接</el-button>
        <el-button type="warning" round @click="handleSendMessage">
          发送消息
        </el-button>
        <el-button type="danger" round>关闭连接</el-button>
      </el-row>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'Index',
    data() {
      return {
        chatMessage: '',
        websock: null,
        sendMessage: '',
      }
    },
    methods: {
      handleConnect() {
        const wsuri = 'ws://localhost:7080/onLineService'
        this.websock = new WebSocket(wsuri)
        this.websock.onmessage = this.websocketonmessage
        this.websock.onopen = this.websocketonopen
        this.websock.onerror = this.websocketonerror
        this.websock.onclose = this.websocketclose
      },
      websocketonopen() {
        //连接建立之后执行send方法发送数据
        let actions = 'hello'
        this.websocketsend(actions)
      },
      websocketonerror() {
        //连接建立失败重连
        this.initWebSocket()
      },
      websocketonmessage(e) {
        //数据接收
        // const redata = JSON.parse(e.data)
        console.log('websockettomessage', e.data)
        let msg = '客服：' + e.data + '\r\n'
        this.chatMessage += msg
      },
      websocketsend(message) {
        //数据发送
        this.websock.send(message)
      },
      websocketclose(e) {
        //关闭
        console.log('断开连接', e)
      },
      handleSendMessage() {
        this.websock.send(this.sendMessage)
        console.log('handleSendMessage', this.sendMessage)
        let msg = '我说：' + this.sendMessage + '\r\n'
        this.chatMessage += msg
        this.sendMessage = ''
      },
    },
  }
</script>

<style scoped></style>
